import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter_rtk/common/common.dart';
import 'package:flutter_rtk/core/flutter_bridge.dart';
import 'package:flutter_rtk/core/plugin_error.dart';
import 'package:flutter_rtk/core/plugin_execute.dart';
import 'package:flutter_rtk/entities/sync_business_entity.dart';
import 'package:flutter_rtk/service/database_service.dart';

class DatabaseOperatePlugin extends PluginExecute {
  @override
  doExecute(BuildContext context, Result result) async {
    var params = jsonDecode(result.data);
    if (params == null || params.isEmpty) {
      result.callback(jsonEncode({'code': -1, 'message': '数据库操作: 缺失必要参数'}));
      return;
    }
    String op = params['op'] ?? "";
    if (op.isEmpty) {
      result.callback(jsonEncode({'code': -1, 'message': '数据库操作: 未知的操作类型'}));
      return;
    }
    // common params
    String business = params['business'] ?? "";
    // business params
    String id = params['id'] ?? "";
    String? text = params['text'];
    String? images = params['images'];
    String? where = params['where'];
    List? whereArgs = params['whereArgs'];
    if (op == "query") {
      // 增加参数：表名，支持查询其他表
      String? tableName = params['tableName'];
      try {
        if (tableName != null) {
          var list = await DatabaseService.to.find(tableName: tableName, where: where, whereArgs: whereArgs);
          result.callback({'code': 0, 'data': list});
          return;
        }
        List<SyncBusinessEntity> list = await DatabaseService.to.findBusinessSync(where: where, whereArgs: whereArgs);
        result.callback({'code': 0, 'data': list});
      } catch (e) {
        showToast("$e");
      }
    } else if (op == "insert") {
      try {
        if (text == null) {
          result.callback(jsonEncode({'code': -1, 'message': '数据库操作: 缺失必要参数'}));
          return;
        }
        String dataId = await DatabaseService.to.insertBusinessSync(business, text, images);
        result.callback({'code': dataId.isEmpty ? -1 : 0, 'data': dataId, 'message': dataId.isEmpty ? '操作失败' : ''}); // String ==> id
      } catch (e) {
        showToast("$e");
      }
    } else if (op == "update") {
      try {
        bool isSuccess = await DatabaseService.to.updateBusinessSync(id, text, images); // bool
        result.callback({'code': isSuccess ? 0 : false, 'data': isSuccess, 'message': isSuccess ? '' : '操作失败'});
      } catch (e) {
        showToast("$e");
      }
    } else if (op == "delete") {
      try {
        bool isSuccess = await DatabaseService.to.deleteBusinessSync(id); // bool
        result.callback({'code': isSuccess ? 0 : false, 'data': isSuccess, 'message': isSuccess ? '' : '操作失败'});
      } catch (e) {
        showToast("$e");
      }
    } else {
      throw PluginError("未知的操作类型");
    }
  }
}
